package com.pig4cloud.pig.demo.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.demo.Mapper.CommentMapper;
import com.pig4cloud.pig.demo.Service.CollectionService;
import com.pig4cloud.pig.demo.Service.CommentService;
import com.pig4cloud.pig.demo.Service.UserAndLikeService;
import com.pig4cloud.pig.demo.feign.Entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserAndLikeService userAndLikeService;

    @Autowired
    private CollectionService collectionService;

    @Override
    public int insertComment(Comment comment) {
        return commentMapper.insert(comment);
    }

    @Override
    public List<CommentAndLikeVO> getCommentAndLike(Long id, Long currentUserId, int currentPage, int size) {
        List<Comment> lists = commentMapper.getCommentAndLike(id, (currentPage - 1) * size, size);

        List<CommentAndLikeVO> results = new ArrayList<>();

        for (Comment list : lists) {
            CommentAndLikeVO commentAndLikeVO = new CommentAndLikeVO();
            commentAndLikeVO.setTitle(list.getArticle().getTitle());
            commentAndLikeVO.setAuthor(list.getArticle().getPerson());
            commentAndLikeVO.setCurrentArticleId(list.getArticle().getId());
            commentAndLikeVO.setCommentUsername(list.getUser().getUsername());
            commentAndLikeVO.setUrl(list.getUser().getAvatar());
            commentAndLikeVO.setComment(list.getContent());
            commentAndLikeVO.setLikeNums(list.getConlike().getNum());
            commentAndLikeVO.setPrice(list.getArticle().getPrice());

            CollectionVO collectionVO = collectionService.getByUidAndAid(list.getArticle().getId(), currentUserId);
            commentAndLikeVO.setCollect(collectionVO.isCollection());
            commentAndLikeVO.setCollectionNums(collectionVO.getCollectionNum());

            int total = getCommentTotal(commentAndLikeVO.getCurrentArticleId());
            commentAndLikeVO.setCommentNums(total);

            Userandlike userandlike = userAndLikeService.findByUidAndCid(currentUserId, list.getConlike().getId());
            commentAndLikeVO.setCurrentUserId(userandlike.getUid());
            commentAndLikeVO.setIsLiked(userandlike.getIsLiked());
            commentAndLikeVO.setConlikeId(userandlike.getConlike().getId());

            results.add(commentAndLikeVO);
        }
        return results;
    }

    @Override
    public int getCommentTotal(Long id) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<Comment>();
        if (id != null)
            wrapper.eq("aid", id);
        return commentMapper.selectCount(wrapper);
    }
}
